/*
  EEPROM-backed persistence.
  Keeps lifetime seed count / runtime across power cycles, and stores the
  soil-moisture sensor's dry/wet calibration so field calibration survives
  a reset. Writes are batched (not once per loop) to respect EEPROM's
  ~100k write-cycle endurance.
*/
#ifndef STORAGE_MANAGER_H
#define STORAGE_MANAGER_H

#include <Arduino.h>
#include "Config.h"

struct PersistentData {
  uint16_t magic;
  uint32_t lifetimeSeedCount;
  uint32_t lifetimeRuntimeSeconds;
  int16_t  soilDryRaw;   // ADC reading in fully dry soil (calibration)
  int16_t  soilWetRaw;   // ADC reading in fully saturated soil (calibration)
};

class StorageManager {
public:
  void begin();

  uint32_t lifetimeSeedCount() const { return _data.lifetimeSeedCount; }
  uint32_t lifetimeRuntimeSeconds() const { return _data.lifetimeRuntimeSeconds; }
  int16_t  soilDryRaw() const { return _data.soilDryRaw; }
  int16_t  soilWetRaw() const { return _data.soilWetRaw; }

  // Called frequently
  // or when a calibration value changes 
  void addSeeds(uint32_t n);
  void tickRuntime(unsigned long nowMs);
  void setSoilCalibration(int16_t dryRaw, int16_t wetRaw);
  void resetLifetimeStats();

  void flushIfDue(unsigned long nowMs);
  void flushNow();

private:
  PersistentData _data{};
  bool _dirty = false;
  unsigned long _lastFlushMs = 0;
  unsigned long _lastRuntimeTickMs = 0;
  static constexpr unsigned long SAVE_INTERVAL_MS = 30000; // batch writes every 30s
};

#endif 
